<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/5/7
 * Time: 下午4:05
 */

namespace App\Http\Services;

use App\Http\Model\FinanceCharm;
use App\Http\Model\Gift;
use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\User;
use App\Http\Model\RoomHostMicro;
use App\Http\Model\RoomMicro;
use App\Http\Model\RoomTally;
use App\Lib\rc;
use App\Http\Services\RoomMsgServices;
use Illuminate\Support\Facades\Redis;

class RoomTallyServices extends CommonServices
{
    private $modelGift;
    private $modelRoomMicro;
    private $modelRoomHostMicro;
    private $modelRoomTally;
    private $modelRoom;
    private $modelUser;
    private $lib_rong;
    private $roomMsgService;
    protected $userSendColorGiftInfo = 'COLOR:GIFT:SEND:CHARMINFO:';//zset 用户送礼主播魅力值列表 COLOR:GIFT:SEND:CHARMINFO:{userId} => {int} {userid}
    protected $loveRankOpenStatusKey = 'ROOM:LOVE:RANK:OPEN';//set ROOM:LOVE:RANK:OPEN 开启房间真爱榜的房间集合

    public function __construct()
    {
        $this->modelGift = new Gift();
        $this->modelRoomHostMicro = new RoomHostMicro();
        $this->modelRoomMicro = new RoomMicro();
        $this->modelRoomTally = new RoomTally();
        $this->modelRoom = new Room();
        $this->modelUser = new User();
        $this->lib_rong = new rc();
        $this->roomMsgService = new RoomMsgServices();

        parent::__construct();
    }


    /**
     * 送礼物计数
     * @return array
     */
    public function inc($roomId, $sendUserId, $userIdArr, $giftId, $count)
    {
        $now = time();
        if (empty($this->modelRoomTally->opened($roomId))) {
            return null;
        }
        $gift = $this->modelGift->get_gift($giftId);
        if (empty($gift)) {
            return null;
        }
        //幸运礼物
        if ($gift['gift_type'] == 2) {
            $gift['price'] = $gift['price'] * 0.1;
        }
        $retData = [];
        $sumVal = 0;
        //魅力值缓存
        $charmTotalArr = Redis::ZRANGE($this->userSendColorGiftInfo . $sendUserId, 0, -1, 'WITHSCORES');
        foreach ($userIdArr as $userId) {
            $val = intval($gift['price'] * $count);
            if ($gift['gift_type'] == 5) {
                $val = $charmTotalArr[$userId];
            }
            $allVal = $this->modelRoomTally->inc($roomId, $userId, $val);
            $item = [
                'user_id' => $userId,
                'val' => $allVal,
            ];
            $sumVal += $val;
            $retData[] = $item;
        }

        return ['recv' => $retData];
    }

    /**
     * 根据礼物流水更新送礼物计数
     * @return array
     */
    public function incByGiftStream($roomId, $fromUserId, $streamList)
    {
        if (empty($this->modelRoomTally->opened($roomId))) {
            return null;
        }

        //收礼人累加
        $retData = [];
        $sumVal = 0;
        foreach ($streamList as $val) {

            if (isset($val['hide_msg']) && $val['hide_msg'] == 1) {
                continue;
            }
            if (in_array($val['gift_type'], [5, 9])) {
                continue;
            }
            $num = intval($val['gift_price'] * $val['gift_num']);
            $allVal = $this->modelRoomTally->inc($roomId, $val['user_id'], $num);
            $item = [
                'user_id' => $val['user_id'],
                'val' => $allVal,
            ];
            $sumVal += $num;
            $retData[] = $item;
        }

        return ['recv' => $retData];
    }

    /**
     * 获取所有礼物信息
     * @return array
     */
    public function info($roomId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $data['opened'] = $this->modelRoomTally->opened($roomId);
            $tallyData = $this->modelRoomTally->getValues($roomId);
            if (!empty($tallyData)) {
                $userIds = array_column($tallyData, 'user_id');
                $userList = $this->modelUser->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');
                foreach ($tallyData as $key => $val) {
                    $val['user_uid'] = empty($userList[$val['user_id']]['user_uid']) ? 0 : $userList[$val['user_id']]['user_uid'];
                    $val['nickname'] = empty($userList[$val['user_id']]['nickname']) ? '' : $userList[$val['user_id']]['nickname'];
                    $val['gender'] = empty($userList[$val['user_id']]['gender']) ? 0 : $userList[$val['user_id']]['gender'];
                    $val['head_portrait'] = empty($userList[$val['user_id']]['images'][0]) ? '' : $userList[$val['user_id']]['images'][0];
                    $tallyData[$key] = $val;
                }
            }
            $data['tally_data'] = $tallyData;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    
    /**
     * 开启是否使用计数
     * @return array
     */
    public function open()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $roomId = $this->requestData['room_id'];
            $curUser = $this->user->get_current_user();
            if ($this->modelRoom->get_role($roomId, $curUser['user_id']) == 0) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $this->modelRoomTally->close($roomId);
            $this->modelRoomTally->open($roomId);
            $data['opened'] = 1;

        } while (false);

        return compact('code', 'msg', 'data');

    }

    /**
     * 关闭计数
     * @return array
     */
    public function close()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('room_id', '房间ID', 'int', true, '房间ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $roomId = $this->requestData['room_id'];
            $curUser = $this->user->get_current_user();
            if ($this->modelRoom->get_role($roomId, $curUser['user_id']) == 0) {
                $code = Hint::AUTH_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            $this->modelRoomTally->close($roomId);
            $data['opened'] = 0;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 重制房间指定用户计数
     * @return array
     */
    public function resetUserTally($roomId, $userId, $toUserIds)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //校验权限
            if ($this->modelRoom->get_role($roomId, $userId) == 0) {
                $code = Hint::AUTH_ERROR;
                break;
            }

            //房间开启
            $opened = $this->modelRoomTally->opened($roomId);
            if ($opened != 1) {
                $code = Hint::PARAM_ERROR;
                $msg = '未开启魅力值';
                break;
            }

            //设置
            foreach ($toUserIds as $toUserId) {
                $this->modelRoomTally->setUserTally($roomId, $toUserId, 0);
                $model = new FinanceCharm();
                $model->clearCharmLog($toUserId, $roomId);
            }
            //消息通知
            $tallyData = $this->modelRoomTally->getValues($roomId);
            if (!empty($tallyData)) {
                $this->roomMsgService->broadcastTallyData($roomId, $tallyData);
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 更改房间真爱榜开关状态
     */
    public function changeLoveRank($roomId, $userId, $status)
    {
        do {
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            if ($status == 1) {//开启
                $check = Redis::HGET($this->loveRankOpenStatusKey, $roomId);
                if ($check == 1) {
                    $code = Hint::ERR_NORMAL;
                    $msg = '房间已开启真爱榜无需再次开启.';
                    break;
                }
                Redis::HSET($this->loveRankOpenStatusKey, $roomId, 1);
            } else {
                Redis::HSET($this->loveRankOpenStatusKey, $roomId, 0);
            }
            //消息通知
            $this->roomMsgService->broadcastLoveRankData($roomId, $status);

        } while (false);
        return compact('code', 'data', 'msg');
    }
}